/**
 * Created by rockyren on 14/11/18.
 */
productApp.controller('productIndexController',['$scope','productService',function($scope,productService){

  function loadIndexProduct() {
     productService.get()
       .success(function(data) {
         $scope.classification = data;


         for(var i=0;i<$scope.classification.length;i++) {
           //取得classification的id为1的分类为主推荐分类
           if($scope.classification[i].id == 1) {
             var recommendClassificationArray = $scope.classification.splice(i,1);
             $scope.recommendClassification = recommendClassificationArray[0];
             break;
           }
         }


         var mainRecommend = $scope.recommendClassification.productList.shift();

         $scope.recommend = {
           id: $scope.recommendClassification.id,
           main: mainRecommend,
           minor: $scope.recommendClassification.productList
         }
       })
       .error(function(data){
         console.log(data.error);
       });
  }

  loadIndexProduct();
}]);

productApp.controller('productInfoController',['$scope','$routeParams','$window','productService','cartServices',function($scope,$routeParams,$window,productService,cartServices){
  var productId = $routeParams.productId;

  /**
   * 商品数量模块,使用闭包实现
   * 命名空间为Number
   */

  $scope.Number = (function(){
    //私有的计数变量,默认为1
    var count = 1;

    //返回一个暴露的公有对象
    return {
      minus: function(){
        if(count > 1){
          count--;
        }
      },
      plus: function(){
        if(count < $scope.productInfo.amount){
          count++;
        }
      },
      getCount: function(){
        return count;
      }
    }
  })();


  function loadProduct() {
    productService.show(productId)
      .success(function(data){
        $scope.productInfo = data.baseInfo;

      })
      .error(function(data){
        console.log(data.error);
      });
  }
  loadProduct();


  $scope.addCart = function(){
    cartServices.store({
      id: $scope.productInfo.id,
      count: $scope.Number.getCount()
    })
      .success(function(data){
        $window.location.href = 'cart';
      })
      .error(function(data){
        console.log(data.error);
      });
  }

}]);
